package
{
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;

	public class VTTerm extends Sprite
	{
		private var m_enabled:Boolean;
		private var m_command:TextField = new TextField();
		private var m_textArea:TextField = new TextField();
		private var m_callbackFunction:Function;
		private var m_commandHistory:Array = new Array();
		private var m_historyPointer:int = 0;
		
		public function VTTerm(callback:Function)
		{
			visible = false;
			m_callbackFunction = callback;
			m_command.defaultTextFormat = new TextFormat('courier',12,0xffffff);
			m_textArea.defaultTextFormat = new TextFormat('courier',12,0xffffff);
			addEventListener(Event.ADDED_TO_STAGE, onStageAdd);
		}
		
		public function write(text:String):void{
			m_textArea.appendText(text + '\n');
		}
		
		private function onKeyboardDown(ke:KeyboardEvent):void{
			switch(ke.keyCode){
				case Keyboard.BACKSPACE:
					m_command.replaceText(m_command.text.length-1,m_command.text.length,'');
					break;
				case Keyboard.ENTER:
					m_callbackFunction(m_command.text);
					m_textArea.appendText(m_command.text + '\n');
					m_textArea.autoSize = TextFieldAutoSize.LEFT;
					m_commandHistory.push(m_command.text);
					m_command.text = '';
					m_historyPointer = m_commandHistory.length;
					break;
				case Keyboard.UP:
					m_command.text = m_commandHistory[m_historyPointer-1];
					m_historyPointer--;
					if(m_historyPointer < 1){
						m_historyPointer = m_commandHistory.length;
					}
					break;
				case Keyboard.DOWN:
					
					break;
				default:
					switch(String.fromCharCode(ke.charCode)){
						case '`':
							visible = !visible;
							break;
						default:
							m_command.appendText(String.fromCharCode(ke.charCode));
							break;
					}		
					break;
			}
			
			m_command.autoSize = TextFieldAutoSize.LEFT;
		}
		
		private function onStageAdd(e:Event):void{
			var stage:Stage = e.currentTarget.parent.stage as Stage;
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
			
			this.graphics.clear();
			this.graphics.beginFill(0,.65);
			this.graphics.drawRect(0,0,stage.width, stage.height/2);			
			this.graphics.endFill();
			
			addChild(m_textArea);
			m_command.y = stage.height/2;
			
			var commandBG:Sprite = new Sprite();
			commandBG.graphics.beginFill(0);
			commandBG.graphics.drawRect(0,stage.height/2, stage.width, 15);
			commandBG.graphics.endFill();
			commandBG.addChild(m_command);
			
			addChild(commandBG);
		}
		
	}
}